package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"video_08_28/internal/model"
	"video_08_28/internal/params"
)

func AddVideo(c *gin.Context) {
	var req params.AddVideoForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var video model.Video

	video = model.Video{
		UserId:   req.UserId,
		Title:    req.Title,
		VideoUrl: req.VideoUrl,
		Info:     req.Info,
	}

	err := video.AddVideo()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "发布失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "发布成功",
		"data":    video.Id,
	})
}

func FindVideo(c *gin.Context) {
	var req params.FindVideoForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	page, _ := strconv.Atoi(strconv.Itoa(req.Page))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(strconv.Itoa(req.PageSize))
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	var video model.Video

	findVideo, err := video.FindVideo(req.Title, page, pageSize)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "查找失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    findVideo,
	})
}

func GetVideo(c *gin.Context) {
	var req params.GetVideoForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	var video model.Video

	video.Id = req.Id

	err := video.GetVideo()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "查找失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    video,
	})
}
